package cn.daomeng.firebird.core.exception;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Component;

import cn.daomeng.firebird.core.log.LogFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * @author gaoqing.li
 * @date 2019/4/15
 **/
@Component
public class I18nMessageService {

    private MessageSource messageSource;
    @Value("${spring.messages.basename:i18n/messages}")
    private String basename;

    @Value("${spring.messages.cache-seconds:-1}")
    private long cacheMillis;

    @Value("${spring.messages.encoding:UTF-8}")
    private String encoding;
    /**
     * 初始化
     * @return
     */
    private MessageSource initMessageSource() {
        ReloadableResourceBundleMessageSource messageSource=new ReloadableResourceBundleMessageSource();
        LogFactory.info("baseName====>:" + this.basename);
        messageSource.setBasename(basename);
        messageSource.setDefaultEncoding(encoding);
        messageSource.setCacheMillis(cacheMillis);
        return messageSource;
    }
    /**
     * 设置当前的返回信息
     * @param locale
     * @param code
     * @return
     */
    public String getMessage(Locale locale, String code, String[] value){
        if(messageSource==null){
            messageSource=initMessageSource();
        }
        String result=null;
        try {
            result = messageSource.getMessage(code, value, locale);
        } catch (NoSuchMessageException e) {
            LogFactory.error("Cannot find the error message of internationalization, return the original error message.");
        }
        if(result==null){
            return code;
        }
        return result;
    }
}